package com.example.test.service;

import com.example.test.model.Order;
import com.example.test.model.User;
import com.example.test.repository.UserRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void createUser(User user) {
        userRepository.save(user);

        if (user.getCreatedAt() == null)
            user.setCreatedAt(getUserById(user.getId()).getCreatedAt());

        if (user.getUpdatedAt() == null)
            user.setUpdatedAt(getUserById(user.getId()).getUpdatedAt());
    }

    public User getUserById(long id) {
        return userRepository.findById(id);
    }

    public List<User> getUsers(int offset, int limit) {
        return userRepository.find(offset, limit);
    }

    public List<Order> getRecentOrdersByUserId(long userId) {
        return userRepository.findRecentOrdersByUserId(userId);
    }

    public void updateUser(User user) {
        userRepository.update(user);

        if (user.getCreatedAt() == null)
            user.setCreatedAt(getUserById(user.getId()).getCreatedAt());

        if (user.getUpdatedAt() == null)
            user.setUpdatedAt(getUserById(user.getId()).getUpdatedAt());
    }

    public void deleteUserById(long id) {
        userRepository.deleteById(id);
    }
}
